package messagebeans;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.NamingException;

import org.apache.activemq.ActiveMQConnectionFactory;

public class PublisherBean {

	protected String jmsServerUrl = "tcp://0.0.0.0:61616";

	private static final String PUBLISHER_TOPIC_NAME = "jms/PublishTopic";

	private Connection connection;
	private Session session;
	private MessageProducer messageProducer;

	protected PublisherBean() {
		super();
	}

	public static PublisherBean newPublisherBean() throws JMSException,
			NamingException {
		PublisherBean publisherBean = new PublisherBean();
		publisherBean.initialize();
		return publisherBean;
	}

	protected void initialize() throws JMSException, NamingException {
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
				jmsServerUrl);
		connection = connectionFactory.createConnection();
		session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		Destination publisherTopic = session.createTopic(PUBLISHER_TOPIC_NAME);
		messageProducer = session.createProducer(publisherTopic);
		// messageProducer.setTimeToLive(10000);
		// messageProducer.setDeliveryMode(DeliveryMode.PERSISTENT);

		connection.start();
	}

	public void notify(String message) throws JMSException {
		TextMessage textMessage = session.createTextMessage(message);
		messageProducer.send(textMessage);

		// Output sent message
		System.out.println("Sent Message in Topic Channel -- "
				+ PUBLISHER_TOPIC_NAME);
		System.out.println("\tTime:       " + System.currentTimeMillis()
				+ " ms");
		System.out.println("\tMessage ID: " + textMessage.getJMSMessageID());
		
		System.out.println("\tContents:   " + textMessage.getText());
	}

	public void release() throws JMSException {
		if (connection != null) {
			connection.stop();
			connection.close();
		}
	}
}
